package com.itheima.case2.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
//无需设置路径: 只是一个工具
//@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //1.获取方法名
        String url = request.getRequestURI();
        int lastIndex = url.lastIndexOf('/');
        String method = url.substring(lastIndex + 1,url.length());

        try {
//        1. 获取Class对象
            Class<?>  clazz = this.getClass();
//        2. 获取指定的方法 : 方法名+参数列表才能唯一确定一个方法
            Method rfMethod = clazz.getDeclaredMethod(method,HttpServletRequest.class,HttpServletResponse.class);
//        3. 调用方法
            rfMethod.setAccessible(true);
            rfMethod.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}